<?php


namespace App\Http\Middleware;


use App\Http\Common\JWT;
use App\Models\AdminUser;
use Closure;

class CheckToken
{
    public function handle($request, Closure $next)
    {
        $header = $request->header('authorization');
        if (!env('CHECK_TOKEN')) {
            $user = AdminUser::with('community')->select('id', 'username', 'name', 'password', 'property_id')->first();
            $request->merge(['userinfo' => $user]);
            return $next($request);
        }
        if (!$header) {
            return makeResponse([], '登录失效!', 402);
        };
//        $token = substr($header, 7);
//        $token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhZG1pbiIsImlhdCI6MTU2NTE0Njc0OCwibmFtZSI6IjEyMyIsInBhc3MiOiIxMjMiLCJqdGkiOiJ0b2dvamlhYmFvIn0.mV4VaCiubJ1vr1VDhp4XUKj7PO59jdIpOAgFqMn4B1k';
        $jwtToken = JWT::verifyToken($header);

        if (isset($jwtToken['jti']) && $jwtToken['jti'] !== env('JWT_CODE') && env('CHECK_TOKEN')) {
            return makeResponse([], '签名错误', 402);
        } else {
            $user = AdminUser::with('community')->where(['username' => $jwtToken['name']])->select('id', 'username', 'name', 'password', 'property_id')->first();


            if (count($user->community) == 0) {
                return makeResponse([], '请绑定小区~', 500);
            }

            $status = passwordVerify($jwtToken['pass'], $user->password);
            unset($user->password);
            unset($user->community);
            if ($status) {
                $request->merge(['userinfo' => $user]);

            } else {
                return makeResponse([], 'Token验证失败~', 402);
            }
        }
        return $next($request);
    }
}